<template>
  <div>
    <div class="search-term">
      <el-form :inline="true" :model="searchInfo">
        <el-form-item label="应用">
          <el-select clearable filterable placeholder="请选择" v-model="searchInfo.apps_name">
            <el-option
                    v-for="(item, i) in appOptions"
                    :key=i
                    :label=item
                    :value=item>
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="环境" prop="env">
          <el-select  placeholder="环境" clearable v-model="searchInfo.deploy_env" style="width: 200px">
            <el-option
                    v-for="(item, i) in envOptions"
                    :key="i"
                    :label="item.item_name"
                    :value="item.item_value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button
                  class="filter-item"
                  type="primary"
                  icon="el-icon-search"
                  :disabled="disabledBuild"
                  @click="handleRollbackBtn"
          >开始重启</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div>
      请选择环境进行重启
    </div>
    <div class="console">
              <textarea class="log" id="logArea"  placeholder="">
                {{buildLogTitle}}
                {{buildLogContent}}
              </textarea>
    </div>
  </div>
</template>

<script>
  import { getDeployBuildList } from "@/api/deploy_build";
  import { getDeployAppList } from "@/api/deploy_app";
  import infoList from '@/mixins/infoList'
  import { startJenkinsJobBuild, getJenkinsBuildJobLogs } from "@/api/deploy_jenkins";


  export default {
    name: "restart",
    mixins: [infoList],
    data() {
      return {
        searchInfo: {
          apps_name: '',   //
        },
        apps_job_name: '',
        appOptions: [],
        envOptions: [],
        deploy_type: "restart", // 重启
        disabledBuild:false,
        buildLogTitle: '支持后端重启\n重启提示：重启过程不要断开浏览器，如断开需要查看重启日志请到发布历史中查看',
        buildLogContent: '',
      }
    },
    methods: {
      getJenkinsBuildJobLogs(build_number, apps_job_name) {
        getJenkinsBuildJobLogs({build_number: build_number, apps_job_name: apps_job_name, deploy_type: this.deploy_type}).then(res => {
          if (res.code == 0 ) {
            this.buildLogContent = res.data.log
          }
        })
      },
      handleRollbackBtn() {
        this.$confirm("是否确定要重启?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
          .then(async () => {
            this.visible = false;
            this.handleRollback()
          })
          .catch(() => {
            this.$message({
              type: "info",
              message: "已取消重启"
            });
          });
      },
      handleRollback() {
        // console.log('开始重启')
        this.apps_job_name = this.searchInfo.deploy_env + "-" +this.searchInfo.apps_name
        startJenkinsJobBuild({apps_job_name: this.apps_job_name, "if_restart": true, "branch_name": "-"}).then(res => {
          if (res.code == 0) {
            this.$message({
              type: 'success',
              message: '重启触发成功，等待重启，请关注日志',
            })
            // 禁用重启按钮
            this.disabledBuild = true
            // 获取日志

            this.buildLogTitle = '等待执行中，本次重启日志:\n'
            // 打开websocket

            this.openWS(res.data.build_number, this.apps_job_name)

          }
        })
      },
      openWS(build_number, apps_job_name) {
        this.ws = new WebSocket(`ws://${location.hostname}:8081/base/deploy/jenkins/getJenkinsBuildJobLogsWS?apps_job_name=${apps_job_name}&build_number=${build_number}&deploy_type=${this.deploy_type}`);

        this.ws.onopen = (event) => {
          console.log('Ws Connection open', event);

        }
        this.ws.onclose = (event) =>   {
          console.log('Ws Connection closed',event);

        }

        // 使用箭头函数 但最简单的两种方法是使用箭头函数，它没有this绑定，因此允许您访问父级this
        this.ws.onmessage = (event) => {
          // console.log('build log updated');
          // console.log(event.data)
          // 每次事件给的都是全量数据
          this.buildLogContent = event.data
          if (this.buildLogContent.indexOf("Finished:") !== -1) {
            this.disabledBuild = false  // 完成构建放开按钮
          }
        }

      },
    },
    created() {
      getDeployAppList({'page':1, 'pageSize':500}).then(res => {
        if (res.code == 0 ) {
          this.appOptions = res.data.list.filter(x => x.apps_type== "service").map(x => {return x.apps_name})
        } else {
          this.$message({
            type: 'error',
            message: '网络请求失败',
          })
        }

      })
      this.envOptions = this.getDicItemList('env_name')
      console.log(this.envOptions)
    }

  }
</script>

<style scoped>
  .log{
    width: 95%;
    line-height: 1.5em;
    height: 500px;
    resize: none;
    border: 1px solid #ddd;
    background: #000;
    color: #fff;
  }

  .rollback-tip {
    width: 95.5%;
    background-color: yellow;
    display: inline-block;
  }

</style>